const express = require('express')
const cors = require('cors')
const fs = require('fs');
const { channel } = require('diagnostics_channel');
const { log } = require('console');
let router = express.Router()
const multer = require('multer');
const path = require('path');
// 配置存储,将封面图片存储到指定位置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public') // 保存的路径，备注：需要自己创建
  },
  filename: function (req, file, cb) {
    // 根据articleid生成文件名
    cb(null, req.query.id+'.jpg')
  }
});

// 使用配置创建 multer 实例
const upload = multer({ storage: storage });

router.post('/api/register', (req, res) => {
  const data = {
    token: req.body.token,
    code: req.body.code
  }
  res.send(data)
})
router.post('/api/login', (req, res) => {
  const data = {
    token: req.body.token,
    code: req.body.code
  }
  res.send(data)
})
router.post('/my/info', (req, res) => {
  // 该data对象是一个用户信息对象
  console.log(req.body);
  const data = {
    code: req.body.code,
    token: req.body.token,
    info: req.body
  }
  res.send(data)
})
router.get('/api/channel', (req, res) => {
  let data = ""
  try {
    data = fs.readFileSync('article.json', 'utf8');
  } catch (err) {
    console.error(err);
  }
  res.send({
    code: 0,
    channeldata: JSON.parse(data).channel
  })
})
router.put('/api/addchannel', (req, res) => {
  let data = ""
  try {
    data = fs.readFileSync('article.json', 'utf8');
  } catch (err) {
    console.error(err);
  }
  let newdata = JSON.parse(data)
  newdata.channel.push({
    channelname: req.body.channelname,
    channelothername: req.body.channelothername
  })
  try {
    fs.writeFileSync('./article.json', JSON.stringify(newdata), 'utf8');
    console.log('文件写入成功');
  } catch (err) {
    console.error(err);
  }
  res.send({
    code: 0
  })
})
router.post('/api/emitchannel', (req, res) => {
  let data = ""
  try {
    data = fs.readFileSync('article.json', 'utf8');
  } catch (err) {
    console.error(err);
  }
  let newdata = JSON.parse(data)
  newdata.channel[req.body.index].channelname = req.body.channelname
  newdata.channel[req.body.index].channelothername = req.body.channelothername
  try {
    fs.writeFileSync('./article.json', JSON.stringify(newdata), 'utf8');
    console.log('文件写入成功');
  } catch (err) {
    console.error(err);
  }
  res.send({
    code: 0
  })
})
router.delete('/api/delchannel', (req, res) => {
  let data = ""
  try {
    data = fs.readFileSync('article.json', 'utf8');
  } catch (err) {
    console.error(err);
  }
  let newdata = JSON.parse(data)
  newdata.channel.splice(req.query.id, 1)
  try {
    fs.writeFileSync('./article.json', JSON.stringify(newdata), 'utf8');
    console.log('文件写入成功');
  } catch (err) {
    console.error(err);
  }
  res.send({
    code: 0
  })
})
router.get("/api/manage", (req, res) => {
  let data = ""
  try {
    data = fs.readFileSync('article.json', 'utf8');
  } catch (err) {
    console.error(err);
  }
  let newdata = JSON.parse(data).manage
  // 筛选
  if (req.query.classification == '') {
  // 如果文章分类是空字符串不进行筛选
  } else {
    newdata = newdata.filter((ele) => {
      return ele.classification == req.query.classification && ele.state == req.query.state
    })
  }
  // console.log(newdata);
  // 将数据分页
  let pre = (req.query.currentPage - 1) * (req.query.pagesize)

  if (req.query.pagesize < newdata.length) {
    newdata.splice(0, pre)
    newdata.splice(req.query.pagesize, newdata.length - req.query.pagesize)
  }

  res.send({
    code: 0,
    total: JSON.parse(data).manage.length,
    artlist: newdata
  })
})
router.post('/api/publish',upload.single('articlecover'),(req,res)=>{
  console.log(req.body.articleid,"body");
  // 发布文章操作
  //   获取年、月、日拼接成指定的格式
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份加1，并使用padStart来确保是两位数
  const day = String(now.getDate()).padStart(2, '0'); // 使用padStart来确保是两位数
  const formattedDate = `${year}/${month}/${day}`;

  let data = ""
  try {
    data = fs.readFileSync('article.json', 'utf8');
  } catch (err) {
    console.error(err);
  }
  let newdata = JSON.parse(data)
  if(req.body.isedit=="true"){
    console.log(req.body.oldarticleid);
    console.log(req.body.articleid);
    newdata.manage.forEach(ele => {
      if(ele.articleid==req.body.oldarticleid){
        ele.title=req.body.title
        ele.classification= req.body.classification,
        ele.publishtime =formattedDate,
        ele.state=req.body.state,
        ele.articleid=req.body.articleid,
        ele.content=req.body.content
      }
    });
  }else{
    newdata.manage.push( {
      "title": req.body.title,
      "classification": req.body.classification,
      "publishtime": formattedDate,
      "state": req.body.state,
      "articleid":req.body.articleid,
      "oldarticleid":req.body.oldarticleid,
      "content":req.body.content
    },)
  }
  try {
    fs.writeFileSync('./article.json', JSON.stringify(newdata), 'utf8');
    console.log('文件写入成功');
  } catch (err) {
    console.error(err);
  }

  res.send({
    code: 0
  })
})
router.delete("/api/delarticle",(req,res)=>{
  let data = ""
  try {
    data = fs.readFileSync('article.json', 'utf8');
  } catch (err) {
    console.error(err);
  }
  let newdata = JSON.parse(data)
  newdata.manage.forEach((ele,index) => {
    if(ele.articleid==req.query.id){
      newdata.manage.splice(index,1)
    }
  });
  try {
    fs.writeFileSync('./article.json', JSON.stringify(newdata), 'utf8');
    console.log('文件写入成功');
  } catch (err) {
    console.error(err);
  }
  res.send({
    code:0
  })
})
const app = express()
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors())
app.use(router)
app.listen(9000, function () {
  console.log('9000端口的监听已开启');
})